import React from 'react';
import './crmDeposit.less';
import { Layout, Breadcrumb, Icon, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');
const keyword = sessionStorage.getItem('keyword');//前台权限判断

class CrmDepositForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            addDepositVisible: false, //新增弹出框
            visible1: false, //删除弹出框
            visible2: false, //修改弹出框
            selectedRowKeys: [],//选中的行
            goodsinfolist: [],//订金支付类型
            pagesize: 20,// 每页显示的页数
            depositTypeCount: 0,//客户来源条数
            pageindex: 1,// 当前页
            paytypename: '',//搜索关键词
            recdata: [], //下拉框获取的数据
            editRecord: {},
        }
    }

    componentDidMount() {
        this.getDepositTypeList();
        this.GetAllProHisPrice()
    }


    //定金支付类型列表
    getDepositTypeList() {
        $.ajax({
            url: `${config.CrmSettings}/crm_paytype/GetPayTypeList`,
            type: "post",
            headers: { Authorization: 'Bearer ' + token },
            data: {
                pagesize: this.state.pagesize,
                pageindex: this.state.pageindex,
                paytypename: this.state.paytypename,
            },
            success: res => {
                console.log(res)
                if (res.code === 200) {
                    this.setState({
                        goodsinfolist: res.data,
                        depositTypeCount: res.datacount,
                    });
                } else {
                    message.error('服务器繁忙，请稍后再试。', 1);
                }
            }
        })
    }

    GetAllProHisPrice() {
        $.ajax({
            url: `${config.CrmSettings}/crm_paytype/BindPayType`,
            type: "post",
            headers: { Authorization: 'Bearer ' + token },
            success: res => {
                console.log('下拉框获取的数据', res)
                if (res.code == 200) {
                    const data = res.data;
                    let row = [];
                    row.push(<Option key={0} value="0">无</Option>)
                    if (data.length > 0) {
                        data.forEach((fele, i) => {
                            row.push(<Option key={fele.id} value={fele.id.toString()}>{fele.paytypename}</Option>);
                        });
                        this.setState({
                            recdata: row,
                        });
                    } else {
                        message.error('服务器繁忙，请稍后再试', 1);
                    }
                }
            }
        })
    }

    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.getDepositTypeList();
        });
    }
    //改变每页条数
    handleSizeChange(current, pagesize) {
        this.setState({
            pageindex: 1,
            pagesize: pagesize
        }, () => {
            this.getDepositTypeList();
        });
    }

    //搜索
    searchDepositType(e) {
        this.setState({
            pageindex: 1,
            paytypename: this.props.form.getFieldValue('txt_Inkey')
        }, () => {
            this.getDepositTypeList()
        });
    }

    //重置
    ResetBtn() {
        this.props.form.resetFields();
        this.setState({
            pageindex: 1,
            paytypename: '',
        }, () => {
            this.getDepositTypeList();
        });
    }

    //新增弹出框事件
    addDepositType() {
        this.props.form.resetFields(['addpaytypename', 'addparentid', 'addpaytypedescribtion'])
        this.setState({
            addDepositVisible: true,
        });
    }
    handleAddDepositType() {
        this.props.form.validateFields(['addpaytypename', 'addparentid', 'addpaytypedescribtion'], (err, values) => {
            if (!err) {
                console.log(values)
                $.ajax({
                    url: `${config.CrmSettings}/crm_paytype/AddPayType`,
                    type: "post",
                    headers: { Authorization: 'Bearer ' + token },
                    data: {
                        paytypename: values.addpaytypename,
                        parentid: values.addparentid,
                        paytypedescribtion: values.addpaytypedescribtion,
                    },
                    success: res => {
                        console.log('ccccc', res)
                        if (res.code == 200) {
                            this.getDepositTypeList();
                            this.GetAllProHisPrice();
                            this.setState({
                                addDepositVisible: false,
                            });
                        } else if (res.code == 202) {
                            message.error('此定金支付名已存在，请重新输入！', 1);
                        } else {
                            message.error('服务器繁忙，请稍后再试', 1);
                        }
                    }
                })
            } else {
                message.error('请正确填写必要的信息，再提交', 1);
            }
        });
    }
    cancelAddDepositType() {
        this.setState({
            addDepositVisible: false,
        });
    }

    //删除弹出框事件
    showModal1() {
        if (this.state.selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的数据！', 1);
        } else {
            this.setState({
                visible1: true,
            });
        }
    }
    handleOk1() {
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的数据！', 1);
        } else {
            $.ajax({
                url: `${config.CrmSettings}/crm_paytype/DelPayType`,
                type: "post",
                headers: { Authorization: 'Bearer ' + token },
                data: {
                    id: selectedRowKeys.toString()
                },
                success: res => {
                    console.log(res)
                    if (res.code == 200) {
                        message.success('定金支付类型删除成功！', 1);
                        this.GetAllProHisPrice();
                        this.setState({
                            pageindex: 1,
                            visible1: false,
                            selectedRowKeys: [],
                        }, () => this.getDepositTypeList());
                    } else {
                        message.error('服务器繁忙，请稍后再试', 1);
                    }
                }
            })
        }
    }
    handleCancel1() {
        this.setState({
            visible1: false,
        });
    }
    //修改弹出框事件
    showModal2(record) {
        this.props.form.setFieldsValue({
            paytypedescribtion: record.paytypedescribtion,
        });
        this.setState({
            visible2: true,
            editRecord: record,
        });
    }
    handleOk2() {
        this.props.form.validateFields(['paytypedescribtion'], (err, values) => {
            if (!err) {
                console.log(values)
                $.ajax({
                    url: `${config.CrmSettings}/crm_paytype/UpdatePayType`,
                    type: "post",
                    headers: { Authorization: 'Bearer ' + token },
                    data: {
                        id: this.state.editRecord.id,
                        paytypedescribtion: values.paytypedescribtion,
                    },
                    success: res => {
                        if (res.code == 200) {
                            this.getDepositTypeList()
                            this.setState({
                                visible2: false,
                            });
                        } else if (res.code == 202) {
                            message.error('此定金支付名已存在，请重新输入', 1);
                        } else {
                            message.error('服务器繁忙，请稍后再试', 1);
                        }
                    }
                })
            } else {
                message.error('请正确填写必要的信息，再提交', 1);
            }
        });
    }
    handleCancel2() {
        this.setState({
            visible2: false,
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                sm: { span: 6 },
            },
            wrapperCol: {
                sm: { span: 16 },
            },
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ selectedRowKeys });
            },
            getCheckboxProps: record => ({
                disabled: record.paytypeusetimes > 0 || (record.ParentUseTimes && record.ParentUseTimes.length > 0),
            }),
        };
        const columns = [{
            title: '订金类型',
            dataIndex: 'paytypename',
            width: '25%',
        }, {
            title: '使用数量',
            dataIndex: 'paytypeusetimes',
            width: '10%',
        }, {
            title: '备注',
            dataIndex: 'paytypedescribtion',
            width: '30%',
        }, {
            title: '所属父级',
            dataIndex: 'ParenttPayName',
            width: '25%',
        }, {
            title: '操作',
            dataIndex: 'edit',
            width: '10%',
            render: (text, record) => {
                return keyword.includes('crm_paytypeUpdatePayType') ? <div><a onClick={this.showModal2.bind(this, record)}>修改</a></div> : '';
            }
        }];
        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>系统设置</Breadcrumb.Item>
                                <Breadcrumb.Item>订金支付类型设置</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-z'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_Inkey', {
                                            initialValue: ""
                                        })(
                                            <Input className='addetd-a-r' addonBefore="定金类型" placeholder="请输入" />
                                            )
                                    }
                                </FormItem>
                            </div>
                            <Button type="primary" style={{ marginLeft: 50 }} className='member-button' icon="search" onClick={this.searchDepositType.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.ResetBtn.bind(this)}>重置</Button>
                        </div>
                        <div className='chengge-e  your_sa' style={{ marginBottom: 20 }}>
                            {keyword.includes('crm_paytypeAddPayType') ?
                                <Button className='member-button-aa' onClick={this.addDepositType.bind(this)} type='primary' style={{ marginLeft: 20 }}><Icon type="plus" />新增</Button>
                                : ''}
                            <Modal
                                title="新增"
                                visible={this.state.addDepositVisible}
                                onOk={this.handleAddDepositType.bind(this)}
                                onCancel={this.cancelAddDepositType.bind(this)}
                                maskClosable={false}
                            >
                                <div className='baoigg'>
                                    <FormItem
                                        {...formItemLayout}
                                        label="定金类型"
                                        hasFeedback
                                    >
                                        {getFieldDecorator('addpaytypename', {
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                required: true, max: 20, message: '定金类型不能为空，不能超过20个字',
                                            }],
                                        })(
                                            <Input placeholder="请输入定金类型，不超过20个字" />
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="所属类型"
                                    >
                                        {getFieldDecorator('addparentid', {
                                            initialValue: "0"
                                        })(
                                            <Select>
                                                {this.state.recdata}
                                            </Select>
                                            )}
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="备注"
                                    >
                                        {getFieldDecorator('addpaytypedescribtion', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                max: 100, message: '备注不能超过100个字',
                                            }],
                                        })(
                                            <Input type="textarea" style={{ resize: 'none' }} rows={5} placeholder="请输入备注，不超过100个字" />
                                            )}
                                    </FormItem>
                                </div>
                            </Modal>
                            {keyword.includes('crm_paytypeDelPayType') ?
                                <Button className='member-button-aa' onClick={this.showModal1.bind(this)} style={{ width: 100 }} type='primary'>删除</Button> : ''}
                            <Modal
                                title="删除"
                                visible={this.state.visible1}
                                onOk={this.handleOk1.bind(this)}
                                onCancel={this.handleCancel1.bind(this)}
                                maskClosable={false}
                            >
                                <div className='delets_gg'>
                                    <p className='delets_gg1'>温馨提示</p>
                                    <p>删除后不可恢复，是否继续删除？</p>
                                </div>
                            </Modal>
                            <Modal
                                title="修改"
                                visible={this.state.visible2}
                                onOk={this.handleOk2.bind(this)}
                                onCancel={this.handleCancel2.bind(this)}
                                maskClosable={false}
                            >
                                <div className='baoigg'>
                                    <FormItem
                                        {...formItemLayout}
                                        label="定金类型"
                                        hasFeedback
                                    >
                                        <span>{this.state.editRecord.paytypename}</span>
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="所属类型"
                                    >
                                        <span>{this.state.editRecord.ParenttPayName || "无"}</span>
                                    </FormItem>
                                    <FormItem
                                        {...formItemLayout}
                                        label="备注"
                                    >
                                        {getFieldDecorator('paytypedescribtion', {
                                            validateTrigger: 'onBlur',
                                            rules: [{
                                                max: 100, message: '备注不能超过100个字',
                                            }],
                                        })(
                                            <Input type="textarea" style={{ resize: 'none' }} rows={5} placeholder="请输入备注，不超过100个字" />
                                            )}
                                    </FormItem>
                                </div>
                            </Modal>
                        </div>
                        <div className='allgoods-table clearfix'>
                            <Table
                                rowKey="id"
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={this.state.goodsinfolist}
                                pagination={false}
                                bordered
                            />
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                {
                                    this.state.depositTypeCount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.depositTypeCount}条记录
                                </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.depositTypeCount ? this.state.pagesize * this.state.pageindex : this.state.depositTypeCount}条记录，
                                    共{this.state.depositTypeCount}条记录
                                </p>
                                }
                                <Pagination
                                    current={this.state.pageindex}
                                    total={this.state.depositTypeCount || 1}
                                    defaultPageSize={this.state.pagesize}
                                    onChange={this.changePage.bind(this)}
                                    showSizeChanger
                                    pageSizeOptions={['20', '50', '100']}
                                    onShowSizeChange={(current, pagesize) => this.handleSizeChange(current, pagesize)}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </Form >
        )
    }
}

const CrmDeposit = Form.create()(CrmDepositForm);
export default CrmDeposit;